package com.raysweather.android;

import java.io.InputStream;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Displays the radar to the user.
 * @author Matthew Lingelbach
 *
 */
public class Map extends Activity {
	
	private RaysWeather rw;
	private String location = ""; //Closest radar
	private Drawable radar;
	
	// Detects broadcasts from RaysWeather activity
	BroadcastReceiver bReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equalsIgnoreCase("update_two")){    
				update();
			}
		}
	};



	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.radar);
		
		/* Get closest radar */
		rw = RaysWeather.getInstance();
		registerReceiver(bReceiver, new IntentFilter("update_two"));
		if(rw.getRadarLocation() != null)
			update();
	}

	/**
	 * Retrieves an image from the web and makes it
	 * a Drawable.
	 * @param url
	 * @return
	 */
	private Drawable LoadImageFromWebOperations(String url)
	{
		try
		{
			InputStream is = (InputStream) new URL(url).getContent();
			Drawable d = Drawable.createFromStream(is, "src name");
			return d;
		}catch (Exception e) {
			System.out.println("Exc="+e);
			return null;
		}
	}
	
	/**
	 * Updates the view of the activity with a new radar image
	 */
	private void update(){
			location = rw.getRadarLocation();
			radar=LoadImageFromWebOperations("http://raysweather.com/radar_images/N0R_"+location+"_loop.gif");

			((ImageView)findViewById(R.id.radar_image)).setImageDrawable(radar);
//		}
	}

}